﻿using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Furion.DataValidation;
using Furion.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.JsonWebTokens;
using MyProject.Cache;
using MyProject.Util;
using System.Threading.Tasks;

namespace MyProject.WebApi.Handlers
{
    /// <summary>
    /// JWT 授权自定义处理程序
    /// </summary>
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 请求管道
        /// </summary>
        public override bool Pipeline(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            var str = httpContext.Request.Headers["Authorization"].ToString();

            if (str.IsEmpty())
                return false;

            var token = str[7..];

            var result =  JWTEncryption.Validate(token,App.GetOptions<JWTSettingsOptions>());

            // 校验不通过
            if (result.IsValid == false)
                return false;

            // 获取用户
            var userId = result.Token.GetPayloadValue<string>("UserId").ParseToLong();
            var apiToken = result.Token.GetPayloadValue<string>("ApiToken").ParseToString();

            // 说来惭愧，不知道如何在这里注入服务层，故 更高级的验证 交给过滤器实现了
            if (userId.IsEmpty() || apiToken.IsEmpty())
                return false;

            return true;
        }

    }
}